<?php
/**
 * 提现
 * User: lxq
 * Date: 2018/4/26
 * Time: 10:57
 */
defined('InNcPHP') or exit('Access Invalid!');
class pd_cashControl extends  SystemControl {
    private $links = array(
        array('url'=>'act=pd_cash&op=index','lang'=>'nc_manage'),
        //array('url'=>'act=member&op=merchant_edit','lang'=>'nc_edit')
    );
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 提现列表
     */
    public function indexOp()
    {

        /* @var pd_cashModel $pd_cash_model*/
        $pd_cash_model = Model('pd_cash');
        //查询条件
        $condition = array();
        if (isset($_GET['search_sn']) && $_GET['search_sn']) {
            //提现编号
            $condition['pdc_sn'] = $_GET['search_sn'];
        }
        if (isset($_GET['pay_type']) && is_numeric($_GET['pay_type'])) {
            $condition['pdc_type'] = intval($_GET['pay_type']);
        }
        if (isset($_GET['search_status']) && is_numeric($_GET['search_status'])) {
            $condition['pdc_status'] = intval($_GET['search_status']);
        }
        if (isset($_GET['pdc_user_name']) && $_GET['pdc_user_name']) {
            //收款人姓名
            $condition['member_name'] = $_GET['pdc_user_name'];
        }
        if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
            //商家
            $condition['merchant_id'] = intval($_GET['search_merchant']);
        }else{
            $merchant_id = intval($this->admin_info['merchant_id']);
            if($merchant_id>0){
                $condition['merchant_id'] = $merchant_id;
            }
        }
        $cash_list = $pd_cash_model->getPd_cashListPage($condition,'*',15);

        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        $merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');

        Tpl::output('cash_list',$cash_list);
        Tpl::output('merchants',$merchants);
        Tpl::output('status',$pd_cash_model->status);
        Tpl::output('pay_type',$pd_cash_model->pay_type);
        Tpl::output('page',$pd_cash_model->showpage());
        Tpl::output('search',$_GET);
        Tpl::showpage('cash.index');
    }

    /**
     * ajax获取提现信息
     */
    public function ajax_cash_infoOp()
    {
        $pdc_id = intval($_POST['pdc_id']);
        /* @var pd_cashModel $pd_cash_model*/
        $pd_cash_model = Model('pd_cash');
        $info = $pd_cash_model->getPd_cashInfo(array('pdc_id'=>$pdc_id));
        /* @var member_merchantModel $merchant_model */
        //$merchant_model = Model('member_merchant');
        //$data = $merchant_model->getMerchantInfo(array('merchant_id'=>$info['merchant_id']));
        //$info['tariff'] = $data['pd_tariff'];
        //$info['real_amount'] = money($info['pdc_amount'],$data['pd_tariff']);
        exit(json_encode($info));
    }

    /**
     * 处理提现信息
     */
    public function audit_cashOp()
    {
        /* @var pd_cashModel $pd_cash_model*/
        $pd_cash_model = Model('pd_cash');
        $refund_id = intval($_POST['pdc_id']);
        $status = intval($_POST['status']);
        $reason = trim($_POST['reason']);

        /** @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        /** @var pd_logModel $pd_log_model */
        $pd_log_model = Model('pd_log');
        $cash_info = $pd_cash_model->getPd_cashInfo(array('pdc_id'=>$refund_id,'pdc_status'=>0));
        if(empty($cash_info)){
            exit(json_encode(array('res'=>0,'_msg'=>'非法操作')));
        }
        switch($status){
            case 1:
                //同意操作
                Model::beginTransaction();
                try{
                    $res = $pd_cash_model->updatePd_cash(array('pdc_id'=>$refund_id),array(
                        'pdc_payment_time'=>time(),
                        'pdc_status'=>1,
                        'reason'=>$reason,
                    ));
                    if($res){
                        //释放商家的冻结金额
                        if($merchant_model->reduceMerchantMoney($cash_info['merchant_id'],'frozen_money',$cash_info['pdc_amount'])){
                            $this->log('审核提现订单'.'[订单号:'.$cash_info['pdc_sn'].']',1);
                            Model::commit();
                            exit(json_encode(array('res'=>1)));
                        }else{
                            Model::rollback();
                            exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                        }
                    }else{
                        Model::rollback();
                        exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                    }
                }catch(\Exception $e)
                {
                    Model::rollback();
                    exit(json_encode(array('res'=>0,'_msg'=>$e->getMessage())));
                }
                exit(json_encode(array('res'=>0,'_msg'=>'系统出错')));
            case 2:
                //拒绝操作
                Model::beginTransaction();
                try{
                    $res = $pd_cash_model->updatePd_cash(array('pdc_id'=>$refund_id),array(
                        'pdc_payment_time'=>time(),
                        'pdc_status'=>2,
                        'reason'=>$reason
                    ));
                    if($res){
                        //释放商家的冻结金额
                       $re1 = $merchant_model->reduceMerchantMoney($cash_info['merchant_id'],'frozen_money',$cash_info['pdc_amount']);
                        //增加商家可用金额
                       $re2 = $merchant_model->addMerchantMoney($cash_info['merchant_id'],'all_money',$cash_info['pdc_amount']);
                        if($re2 && $re1){
                            $this->log('审核提现订单'.'[订单号:'.$cash_info['pdc_sn'].']',1);
                            $pd_log_model->addPd_log(array(
                                'merchant_id'=>$cash_info['merchant_id'],
                                'lg_member_name'=>$cash_info['member_name'],
                                'lg_type'=>1,
                                'lg_av_amount'=>$cash_info['pdc_amount'],
                                'lg_add_time'=>time(),
                                'lg_desc'=>'提现订单被拒绝['.$cash_info['pdc_sn'].']'.'您收入'.$cash_info['pdc_amount'].'元',
                                'order_sn'=>$cash_info['pdc_sn'],
                                'if_cash'=>1,
                                'order_name'=>'提现退款'
                            ));
                            Model::commit();
                            exit(json_encode(array('res'=>1)));
                        }else{
                            Model::rollback();
                            exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                        }
                    }else{
                        Model::rollback();
                        exit(json_encode(array('res'=>0,'_msg'=>'操作失败')));
                    }

                }catch(\Exception $e){
                    Model::rollback();
                    exit(json_encode(array('res'=>0,'_msg'=>$e->getMessage())));
                }
                exit(json_encode(array('res'=>0,'_msg'=>'系统出错')));

        }
    }

    /**
     * 导出订单
     */
    public function exportOp()
    {
        /* @var pd_cashModel $pd_cash_model*/
        $pd_cash_model = Model('pd_cash');
        //查询条件
        $condition = array();
        if (isset($_GET['search_sn']) && $_GET['search_sn']) {
            //提现编号
            $condition['pdc_sn'] = $_GET['search_sn'];
        }
        if (isset($_GET['pay_type']) && is_numeric($_GET['pay_type'])) {
            $condition['pdc_type'] = intval($_GET['pay_type']);
        }
        if (isset($_GET['search_status']) && is_numeric($_GET['search_status'])) {
            $condition['pdc_status'] = intval($_GET['search_status']);
        }
        if (isset($_GET['pdc_user_name']) && $_GET['pdc_user_name']) {
            //收款人姓名
            $condition['member_name'] = $_GET['pdc_user_name'];
        }
        if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
            //商家
            $condition['merchant_id'] = intval($_GET['search_merchant']);
        }else{
            $merchant_id = intval($this->admin_info['merchant_id']);
            if($merchant_id>0){
                $condition['merchant_id'] = $merchant_id;
            }
        }
        /* @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        if(intval($this->admin_info['merchant_id'])>0){
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1,'merchant_id'=>$this->admin_info['merchant_id']), 'merchant_id,mc_shop_name');
        }else{
            $merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
        }
        $arr = array();
        foreach($merchants as $k => $v){
            $arr[$v['merchant_id']] = $v['mc_shop_name'];
        }
        //每个EXCEL最大条数
        $exportSize = 1000;
        if (!is_numeric($_GET['curpage'])) {
            $count = $pd_cash_model->getPd_cashCount($condition);
            $array = array();
            if ($count > $exportSize) {
                $page = ceil($count / $exportSize);
                for ($i=1; $i<=$page; $i++){
                    $limit1 = ($i -1 ) * $exportSize + 1;
                    $limit2 = $i * $exportSize > $count ? $count : $i * $exportSize;
                    $array[$i] = $limit1 . ' ~ ' . $limit2 ;
                }
                Tpl::output('list',$array);
                Tpl::showpage('export.excel');
            } else {
                $data = $pd_cash_model
                    ->where($condition)
                    ->order('pdc_id desc')
                    ->limit($exportSize)
                    ->select();
                foreach($data as $key => $value){
                    $data[$key]['mc_shop_name'] = $arr[$value['merchant_id']];
                }
                $this->createExcel($data, $pd_cash_model->status ,$pd_cash_model->pay_type);
            }
        } else {
            $limit1 = ($_GET['curpage'] - 1) * $exportSize;
            $limit2 = $exportSize;
            $data = $pd_cash_model
                ->where($condition)
                ->order('pdc_id desc')
                ->limit("$limit1,$limit2")
                ->select();
            foreach($data as $key => $value){
                $data[$key]['mc_shop_name'] = $arr[$value['merchant_id']];
            }
            $this->createExcel($data, $pd_cash_model->status,$pd_cash_model->pay_type);
        }

    }

    /**
     * 创建Excel
     * @param array $data
     * @param array $status
     * @param array $type
     */
    private function createExcel($data, $status,$type) {
        import('libraries.excel');
        $excel_obj = new Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id'=>'s_title','Font'=>array('FontName'=>'宋体','Size'=>'12','Bold'=>'1')));
        //表头
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'提现编号');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'商户名称');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'收款方式');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'收款账号');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'收款人姓名');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'提现金额');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'实际到账(扣除费率)');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'费率');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'处理状态');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'申请时间');
        $excel_data[0][] = array('styleid'=>'s_title','data'=>'处理时间');
        //数据
        foreach ((array)$data as $k=>$v){
            $tmp = array();
            $tmp[] = array('data'=>$v['pdc_sn']);
            $tmp[] = array('data'=>$v['mc_shop_name']);
            $tmp[] = array('data'=>$type[$v['pdc_type']]);
            $tmp[] = array('data'=>$v['pdc_number']);
            $tmp[] = array('data'=>$v['pdc_user_name']);
            $tmp[] = array('data'=>ncPriceFormat($v['pdc_amount']));
            $tmp[] = array('data'=>ncPriceFormat($v['real_amount']));
            $tmp[] = array('data'=>$v['tariff'].'%');
            $tmp[] = array('data'=>$status[$v['pdc_status']]);
            $tmp[] = array('data'=>date('Y-m-d H:i:s',$v['pdc_add_time']));
            $tmp[] = array('data'=>date('Y-m-d H:i:s',$v['pdc_payment_time']));
            $excel_data[] = $tmp;
        }

        $excel_data = $excel_obj->charset($excel_data,CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset('商家提现订单',CHARSET));
        $excel_obj->generateXML($excel_obj->charset('商家提现订单',CHARSET).$_GET['curpage'].'-'.date('Y-m-d-H',time()));
    }


}